<template>
  <basic-dialog :visible="addDeviceDialog"
                minWidth="400px"
                title="添加设备"
                isShowClose
                @submit="submit"
                @close="hideDialog"
                is-show-basic-footer
                :isShowInnerLoading="loading">
    <q-form class="margin-t-20 margin-r-20 margin-l-20" ref="form" greedy>
      <div v-if="isEnergy">
        <yz-input input-type="select"
                  v-model="queryParams.energyType"
                  :rules="[0]"
                  title="能源类型" :options="energyTypeOptions" ></yz-input>
      </div>
      <div v-else>
        <select-tree label="所在位置"
                     :sel-tree="queryParams.location"
                     ref="selectTree"
                     :tree-list="locationOptions"
                     node-key="hash"
                     @treeChange="onChangeTreeNode" />

      </div>
      <fuzzy-search
        v-model.trim="queryParams.devices"
        fuzzyNumber="keyword"
        :isShowValue="false"
        showAllOption
        isForm
        smallSize
        title="设备"
        :rules="[val => val !== null || '请选择设备']"
        :options="devicesOption"
        :fuzzyFunc="getFilter"
      ></fuzzy-search>
      <fuzzy-search
        v-if="!isEnergy"
        v-model.trim="queryParams.productId"
        fuzzyNumber="keyword"
        :isShowValue="false"
        showAllOption
        isForm
        smallSize
        title="物模型"
        :rules="[val => val !== null || '请选择物模型']"
        :options="deviceTypeOptions"
        :filterByFe="true"
      ></fuzzy-search>
    </q-form>
  </basic-dialog>
</template>

<script>
import SelectTree from 'src/components/select-tree'
import { getDeviceIds, getOrganize } from '../../../../../boot/statistics/device-rate'
import { defaultSchemesClearer } from '../../../../../assets/js/util'
import {
  getEnergyBindDevice,
  getEnergyDevices,
  getEnergyTypeList,
  getPlcBindDevice
} from '../../../../../boot/miot/plc-list'

export default {
  name: 'set-device-dialog',
  components: {
    SelectTree
  },
  props: {
    addDeviceDialog: {
      type: Boolean,
      default: false
    },
    controllerType: {
      type: String,
      default: ''
    },
    tabList: {
      type: Array,
      default: () => []
    },
    deviceTypeOptions: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    isPlc () {
      return this.controllerType === '1'
    },
    isEnergy () {
      return this.controllerType === '2'
    },
    useDeviceId () {
      return [...this.plcBindDevice, ...this.energyBindDevice]
    },
    devicesOption () {
      return this.devicesAllOption.filter(deviceAll => this.tabList.findIndex(tab => deviceAll.id === tab.deviceId) === -1 && this.useDeviceId.findIndex(id => id === deviceAll.id) === -1)
    }
  },
  watch: {
    // controllerType: {
    //   immediate: true,
    //   handler (val) {
    //     if (this.isPlc) {
    //       this.getOrganize()
    //     } else if (this.isEnergy) {
    //       this.getEnergyTypeList()
    //     }
    //   }
    // },
    'queryParams.energyType' (val) {
      if (val) {
        this.getEnergyDevices(val)
      }
    },
    async addDeviceDialog (val) {
      if (val) {
        if (this.isPlc) {
          await this.getPlcBindDevice()
          this.getOrganize()
        } else if (this.isEnergy) {
          await this.getEnergyBindDevice()
          this.getEnergyTypeList()
        }
      }
    }
  },
  data () {
    return {
      deviceDialog: false,
      loading: false,
      locationOptions: [], // 所在位置数据源
      devicesAllOption: [],
      energyTypeOptions: [],
      plcBindDevice: [],
      energyBindDevice: [],
      queryParams: {
        location: {}, // 所在位置
        devices: '',
        energyType: ''
      }
    }
  },
  methods: {
    hideDialog () {
      this.$emit('close')
    },
    getFilter (val) {
      return new Promise(resolve => {
        const res = {
          code: '1200',
          data: [],
          message: ''
        }
        setTimeout(() => {
          if (val) {
            res.data = this.devicesOption.filter(item => {
              return item.label.toLowerCase().indexOf(val.toLowerCase()) > -1
            })
            resolve(res)
          } else {
            res.data = this.devicesOption
            resolve(res)
          }
        }, 500)
      })
    },
    // 获取组织机构树
    getOrganize () {
      getOrganize().then(res => {
        // 去除 default 节点
        let clearTree = defaultSchemesClearer.clear(res.data)

        // 重新组织 tree
        clearTree.forEach(reorganize)

        function reorganize (node) {
          // 如果当前节点是工位，将 opname 挪到 label
          if (node.level === 5) {
            node.label = node.opname
          }

          // 为节点添加唯一键，用于 tree 组件标识唯一节点
          node.uniqueKey = node.level + ':' + node.id

          if (node.children instanceof Array) {
            node.children.forEach(reorganize)
          }
        }

        this.locationOptions = clearTree
        this.selectFirstLocation()
      })
    },
    // 选中第一个组织
    selectFirstLocation () {
      if (this.locationOptions.length === 0) {
        return
      }

      const first = this.locationOptions[0]
      this.queryParams.location.id = first.id
      this.queryParams.location.level = first.level
      this.queryParams.location.label = first.label
      this.queryParams.location.hash = first.hash
      // eslint-disable-next-line no-unused-expressions
      this.$refs.selectTree?.setValue(this.queryParams.location)
      this.getDevices(first.id, first.level)
    },
    // 选择组织机构树节点 *
    onChangeTreeNode (val) {
      this.devicesAllOption = []
      this.queryParams.devices = ''
      if (val.id && val.label && val.hash) {
        this.queryParams.location.id = val.id
        this.queryParams.location.level = val.level
        this.queryParams.location.label = val.label
        this.queryParams.location.hash = val.hash
        this.queryParams.station = null
        this.getDevices(val.id, val.level)
      } else {
        this.selectFirstLocation()
        this.queryParams.station = null
      }
    },
    // 获取能耗设备类型
    getEnergyTypeList () {
      getEnergyTypeList().then(res => {
        const data = res.data
        if (data?.length > 0) {
          this.energyTypeOptions = data.map(item => ({
            label: item.energyTypeName,
            value: item.energyTypeId
          }))
        }
      })
    },
    // 获取能耗的设备
    getEnergyDevices (energyTypeId) {
      getEnergyDevices(energyTypeId).then(res => {
        const data = res.data
        const result = data.map(item => ({
          label: `${item.instruName}(${item.instruCode})`,
          value: item.instruId,
          id: item.instruId,
          name: item.instruName,
          assetNumber: item.instruCode
        }))
        this.devicesAllOption = result
        if (this.devicesOption.length > 0) {
          this.queryParams.devices = this.devicesOption[0].value
        } else {
          this.queryParams.devices = ''
        }
      })
    },
    // 获取组织下设备列表
    getDevices (schemeId, schemeLevel) {
      getDeviceIds(schemeId, schemeLevel).then(res => {
        const ret = res.data
        const member = ret.list.map(v => {
          const item = v
          item.label = `${v.name}(${v.assetNumber || '--'})`
          item.value = v.id
          return item
        })
        this.devicesAllOption = member
        if (this.devicesOption.length > 0) {
          this.queryParams.devices = this.devicesOption[0].value
        } else {
          this.queryParams.devices = ''
        }
      })
    },

    submit () {
      const deviceInfo = this.devicesOption.find(item => item.value === this.queryParams.devices)
      const obj = {
        name: deviceInfo.assetNumber,
        label: `${deviceInfo.name}(${deviceInfo.assetNumber})`,
        deviceId: deviceInfo.id,
        productId: this.queryParams.productId
      }
      this.$emit('addDevice', obj)
    },

    getPlcBindDevice () {
      return new Promise(resolve => {
        getPlcBindDevice().then(res => {
          const data = res.data
          this.plcBindDevice = data.map(item => item.id)
          resolve()
        })
      })
    },

    getEnergyBindDevice () {
      return new Promise(resolve => {
        getEnergyBindDevice().then(res => {
          const data = res.data
          this.energyBindDevice = data.map(item => item.instruId)
          resolve()
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
/deep/ .name{
  width: 75px;
  font-size: 16px;
}
</style>
